/**
 * 树模式-左侧的树组件
 */

import React from 'react';
import { Tree, Loading } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import utils from 'utils';
import { getAllFiles } from 'api';
import ListEmpty from 'atComponents/ListEmpty';
import ColorText from 'components/colorText';
import { navigate } from 'utils/router';
import FileIcon from 'components/fileIcon';
import intl from '../../../../../../../../locale';

const TreeNode = Tree.Node;

const { pathResource, resourceSubject } = window.FORCE;

export default class TreeLeft extends React.Component {
  state = {
    isLoading: false,
  };

  componentDidMount() {
    this.setState({
      isLoading: true,
    });

    // 获取所有数据
    getAllFiles()
      .then((res) => {
        this.setState({
          isLoading: false,
        });

        const data = res.slice(1);
        const datTmp = data.map((item) => {
          item.path = `/${item.path}`;
          return item;
        });
        this.props.updateData({
          filterTreeData: datTmp,
        });
      })
      .catch((e) => {
        this.setState({
          isLoading: false,
        });

        console.error(e);
      });
  }

  onTreeItemSelect = (selectedKeys, e) => {
    const { submodules } = this.props;
    const { isLeaf, eventKey: key } = e.node.props;

    // 点击已选中的item
    if (!selectedKeys.length) {
      return false;
    }

    // TODO 如果是文件，则跳转；否则展开子树 aisc不支持？
    if (isLeaf) {
      const path = selectedKeys[0];

      // resourceType === 'commit' 为 submodule
      if (e.node.props.resourceType === 'commit') {
        // 如果path有对应的submodule，则跳转submodule
        const submodule = submodules && submodules.find((item) => item.path === path);
        if (submodule) {
          window.location = submodule.http_homepage_url;
        }
      } else {
        const pathPrefix = `/${pathResource.fullPath}/blob/${utils.revisionEncodeURI(
          resourceSubject.revision,
        )}/`;
        this.jumpTo(pathPrefix + utils.revisionEncodeURI(path), key, path);
      }
    } else {
      console.log(
        intl.get({
          id: 'code-assets.containers.content.filterLeftTree.Expand',
          defaultMessage: '展开',
        }),
      );
    }
  };

  rewriteDocTitle = (key, revision) => {
    const projectName =
      pathResource.fullPath && pathResource.fullPath.split('/')
        ? pathResource.fullPath.split('/')[1]
        : '';
    document.title = [
      key,
      revision,
      projectName,
      intl.get({
        id: 'code-assets.containers.content.filterLeftTree.YunxiaoCodeup',
        defaultMessage: '云效 Codeup',
      }),
    ].join(' · ');
  };

  jumpTo = (path, key, filepath) => {
    const curPath = utils.filepathEncodeURI(path);
    if (curPath === window.location.pathname) {
      return;
    }
    navigate(curPath);
    this.rewriteDocTitle(key, resourceSubject.revision);
    this.props.updateSetSelectedType({
      resourceSubject: {
        subject: 'blob',
        path: filepath || '',
      },
    });
  };

  updateExpandKeys = (keys) => {
    this.props.updateData({
      defaultExpandedKeys: keys,
    });
  };

  getTreeData = () => {
    const { filterTreeData, filterText } = this.props;
    if (!filterText) {
      return utils.transferPath2Tree(filterTreeData);
    }
    const data = filterTreeData.filter((item) => {
      return item.path && item.path.toLowerCase().indexOf(filterText.toLowerCase()) > -1;
    });
    // 文件夹src只有一个child,该child为文件夹，合并转为src/child
    const srcTreeData = utils.transferPath2Tree(data);
    const simplifyFn = function (item) {
      if (!item.children) {
        return item;
      } else if (item.children.length === 1) {
        if (item.children[0].type === 'tree') {
          const newChild = {
            ...item.children[0],
            name: item.children[0].id,
            tilte: item.children[0].id,
          };

          return simplifyFn(newChild);
        } else {
          return item;
        }
      } else {
        const children = item.children.map((it) => {
          return simplifyFn(it);
        });
        return {
          ...item,
          children,
        };
      }
    };
    const distTreeData = srcTreeData.map((item) => {
      return simplifyFn(item);
    });
    return distTreeData;
  };

  getDefaultExpandKeys = (data) => {
    const arr = ['root'];
    const getKeys = (treeData) =>
      treeData.forEach((item) => {
        if (item.type === 'tree') {
          arr.push(item.id);
          if (item.children) {
            getKeys(item.children);
          }
        }
      });

    getKeys(data);
    return arr;
  };

  render() {
    const { selectedKeys, filterText } = this.props;
    const loop = (data) =>
      data.map((item) => {
        return (
          <TreeNode
            label={
              <span>
                {item.type !== 'commit' ? (
                  <React.Fragment>
                    {item.type === 'tree' ? (
                      <YunxiaoIcon type="folder-line" className="file-icon" />
                    ) : (
                      <FileIcon className="file-icon" fileName={item.name} />
                    )}
                  </React.Fragment>
                ) : (
                  <i className="fa fa-archive" />
                )}{' '}
                <span className="display-inline-block">
                  <ColorText name={item.name} filterText={filterText} />
                </span>
              </span>
            }
            key={item.id}
            isLeaf={item.type !== 'tree'}
            resourceType={item.type}
          >
            {item.children && loop(item.children)}
          </TreeNode>
        );
      });

    // 请求中
    if (this.state.isLoading) {
      return (
        <div className="filter-loading-data">
          <Loading />
        </div>
      );
    }

    const treeDataTmp = this.getTreeData();
    if (!filterText || !treeDataTmp.length) {
      return (
        <div className="filter-no-data">
          <ListEmpty
            size="small"
            type="card"
            content=""
            description={
              (!filterText && '请输入文件名搜索') ||
              intl.get({
                id: 'code-assets.containers.content.filterLeftTree.NoData',
                defaultMessage: '暂无数据',
              })
            }
            image="none"
            className="no-content no-btns"
          />
        </div>
      );
    }

    return (
      <React.Fragment>
        <Tree
          defaultExpandedKeys={this.getDefaultExpandKeys(treeDataTmp)}
          selectedKeys={selectedKeys}
          onSelect={this.onTreeItemSelect}
          onExpand={this.updateExpandKeys}
          className="file-tree"
          isLabelBlock
          mode="directory"
          style={{ display: 'inline-block', minWidth: '100%' }}
          animation={false}
        >
          <TreeNode
            label={pathResource.fullPath.split('/')[pathResource.fullPath.split('/').length - 1]}
            key="root"
          >
            {loop(treeDataTmp)}
          </TreeNode>
        </Tree>
      </React.Fragment>
    );
  }
}
